package com.android.gufengmall.cart;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.android.gufengmall.App;
import com.android.gufengmall.R;
import com.android.gufengmall.adapter.ShopCartAdapter;
import com.android.gufengmall.bean.NormalBean;
import com.android.gufengmall.bean.OrderBean;
import com.android.gufengmall.gen.DaoSession;
import com.android.gufengmall.gen.OrderBeanDao;
import com.ocnyang.cartlayout.bean.CartItemBean;
import com.ocnyang.cartlayout.bean.ICartItem;
import com.ocnyang.cartlayout.listener.CartOnCheckChangeListener;

import java.util.ArrayList;
import java.util.List;

public class CartFragment extends Fragment implements ShopCartAdapter.RemoveDataCallBack{

    private RecyclerView mRecyclerView;
    private TextView mTvTitle;
    private TextView mTvEdit;
    private TextView mTvTotal;
    private CheckBox mChkAll;
    private Button mBtnSubmit;

    ShopCartAdapter mAdapter;

    private boolean isEditing;//是否处于编辑状态
    private int totalCount;//购物车商品ChildItem的总数量，店铺条目不计算在内
    private int totalCheckedCount;//勾选的商品总数量，店铺条目不计算在内
    private double totalPrice;//勾选的商品总价格

    private App mMyApp;
    private DaoSession mDaoSession;
    private OrderBeanDao mOrderBeanDao;
    private List<OrderBean> mOrderBeans;
    private ArrayList<CartItemBean> mCartItemBeans;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_cart, container, false);
        initView(root);
        initData();
        initListener();
        return root;
    }

    private void initData() {
        mCartItemBeans = new ArrayList<>();

        mTvTitle.setText(getString(R.string.cart, 0));
        mBtnSubmit.setText(getString(R.string.go_settle_X, 0));
        mTvTotal.setText(getString(R.string.rmb_X, 0.00));

        mMyApp = (App) getActivity().getApplication();
        mDaoSession = mMyApp.getDaoSession();
        mOrderBeanDao = mDaoSession.getOrderBeanDao();

        mOrderBeans = mOrderBeanDao.loadAll();

        getData();
        mRecyclerView.setLayoutManager(new LinearLayoutManager(requireContext()));
        mAdapter = new ShopCartAdapter(requireContext(),mCartItemBeans );
        mAdapter.setOnCheckChangeListener(new CartOnCheckChangeListener(mRecyclerView, mAdapter) {
            @Override
            public void onCalculateChanged(ICartItem cartItemBean) {
                calculate();
            }
        });
        mRecyclerView.setAdapter(mAdapter);
        mAdapter.setRemoveDataCallBack(this);
        registerForContextMenu(mRecyclerView);
    }

    private void initView(View root) {
        mRecyclerView = root.findViewById(R.id.recycler);
        mTvTitle = root.findViewById(R.id.tv_title);
        mTvEdit = root.findViewById(R.id.tv_edit);
        mTvTotal = root.findViewById(R.id.tv_total_price);
        mChkAll = root.findViewById(R.id.checkbox_all);
        mBtnSubmit = root.findViewById(R.id.btn_go_to_pay);
    }

    private void initListener() {
        mTvEdit.setOnClickListener(v -> {
            isEditing = !isEditing;
            mTvEdit.setText(getString(isEditing ? R.string.edit_done : R.string.edit));
            mBtnSubmit.setText(getString(isEditing ? R.string.delete_X : R.string.go_settle_X, totalCheckedCount));
        });
        mChkAll.setOnClickListener(v -> {
            mAdapter.checkedAll(((CheckBox) v).isChecked());
        });
        mBtnSubmit.setOnClickListener(v -> {
            submitEvent();
        });
    }

    /**
     * 统计操作<br>
     * 1.先清空全局计数器<br>
     * 2.遍历所有子元素，只要是被选中状态的，就进行相关的计算操作<br>
     * 3.给相关的 textView 进行数据填充
     */
    private void calculate() {
        totalCheckedCount = 0;
        totalCount = 0;
        totalPrice = 0.00;
        int notChildTotalCount = 0;
        if (mAdapter.getData() != null) {
            for (ICartItem iCartItem : mAdapter.getData()) {
                if (iCartItem.getItemType() == ICartItem.TYPE_CHILD) {
                    totalCount++;
                    if (iCartItem.isChecked()) {
                        totalCheckedCount++;
                        totalPrice += ((OrderBean) iCartItem).getOrderPrice() * ((OrderBean) iCartItem).getOrderAmount();
                    }
                } else {
                    notChildTotalCount++;
                }
            }
        }

        mTvTitle.setText(getString(R.string.cart, totalCount));
        mBtnSubmit.setText(getString(isEditing ? R.string.delete_X : R.string.go_settle_X, totalCheckedCount));
        mTvTotal.setText(getString(R.string.rmb_X, totalPrice));
        if (mChkAll.isChecked() && (totalCheckedCount == 0 || (totalCheckedCount + notChildTotalCount) != mAdapter.getData().size())) {
            mChkAll.setChecked(false);
        }
        if (totalCheckedCount != 0 && (!mChkAll.isChecked()) && (totalCheckedCount + notChildTotalCount) == mAdapter.getData().size()) {
            mChkAll.setChecked(true);
        }
    }

    /**
     * 删除订单
     * @param position 订单下标
     */
    @Override
    public void remoData(int position) {
        if (mOrderBeans.size() == 0) return;
        OrderBean orderBean = mOrderBeans.get(position);
        mOrderBeanDao.delete(orderBean);
    }

    private void submitEvent() {
        if (isEditing) {
            if (totalCheckedCount == 0) {
                Toast.makeText(requireContext(), "请勾选你要删除的商品", Toast.LENGTH_SHORT).show();
            } else {
                mCartItemBeans.clear();
                mOrderBeanDao.deleteAll();
                mAdapter.removeChecked();
                mAdapter.notifyDataSetChanged();
            }
        } else {
            if (totalCheckedCount == 0) {
                Toast.makeText(requireContext(), "你还没有选择任何商品", Toast.LENGTH_SHORT).show();
            } else {
                Intent intent = new Intent(requireContext(),CartDetailsActivity.class);
                startActivity(intent);
            }
        }
    }

    /**
     * 数据初始化尤其重要
     * 1. childItem 数据全部在 GroupItem 数据的下方，数据顺序严格按照对应关系；
     * 2. GroupItem 下的 ChildItem 数据不能为空；
     * 3. 初始化时如果不需要，所有类型的条目都可以不设置ID，GroupItem也不用设置setChilds()；
     * <p>
     * 列表操作时数据动态的变化设置：
     * 1. 通过 CartAdapter 的 addData、setNewData；
     * 2. 单个添加各个条目可以通过对应的 add 方法；
     * 3. 单独添加一个 GroupItem ,可以把它的 ChildItem 数据放到 setChilds 中。
     *
     * @return
     */
    private List<CartItemBean> getData() {
        NormalBean normalBean = new NormalBean();
        normalBean.setMarkdownNumber(1);
        mCartItemBeans.add(normalBean);

        for (int i = 0; i < mOrderBeans.size(); i++) {
            OrderBean orderBean = mOrderBeans.get(i);
            orderBean.setItemType(CartItemBean.TYPE_CHILD);
            mCartItemBeans.add(orderBean);
        }
        return mCartItemBeans;
    }
}
